package Lee_code;

/**
 * @author blh
 * @date 2024年07月03日 9:11
 */
public class Lee_468_73 {
    public String validIPAddress(String queryIP) {
        if (queryIP.isEmpty() || queryIP.charAt(0) == '.' || queryIP.charAt(0) == ':'
                || queryIP.charAt(queryIP.length() - 1) == '.' || queryIP.charAt(queryIP.length() - 1) == ':') {
            return "Neither";
        }

        if (queryIP.indexOf('.')==-1){
            return "Neither";
        }

        String[] ipv4 = queryIP.split("\\.");
        String[] ipv6 = queryIP.split(":");


        if (ipv4.length == 4) {
            return checkIpv4(ipv4);
        }
        if (ipv6.length == 8) {
            return checkIpv6(ipv6);
        }
        return "Neither";
    }

    private String checkIpv4(String[] ipv4) {
        for (String str : ipv4) {
            if (str.isEmpty()) {
                return "Neither";
            }
            // 前缀零
            if (str.length() > 1 && str.charAt(0) == '0') {
                return "Neither";
            }

            // 元素是否都为数字
            for (int i = 0; i < str.length(); i++) {
                if (!Character.isDigit(str.charAt(i))) {
                    return "Neither";
                }
            }
            // 大小
            if (Integer.parseInt(str) > 255) {
                return "Neither";
            }
        }
        return "IPv4";
    }

    private String checkIpv6(String[] ipv6) {
        for (String string : ipv6) {
            if (string.isEmpty() || string.length() > 4) {
                return "Neither";
            }

            for (int i = 0; i < string.length(); i++) {
                if (!Character.isDigit(string.charAt(i))) {
                    if (!Character.isLetter(string.charAt(i))) {
                        return "Neither";
                    }
                    if ((string.charAt(i) >= 'a' && string.charAt(i) <= 'f')
                            || string.charAt(i) >= 'A' && string.charAt(i) <= 'F') {
                    } else {
                        return "Neither";
                    }
                }
            }
        }
        return "IPv6";
    }
}
